<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/8/23 16:33}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\model;
use app\admin\model\order\OrderGoods;
use think\Db;
use think\model;
use app\api\model\User as Usermodel;

class OrderSale extends model
{
    protected $autoWriteTimestamp = 'int';

    protected $name = 'order_sale';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [

    ];

    /**
     * @param $uid 用户id
     * @param $id 订单id
     * @param int $type 0-退货退款,1-退款无需退货
     * @param $moneye 退款金额
     * @param string $cause 退款原因
     * @param string $instructions 退款说明
     * @param string $image 退款图片
     * @param string $phone 联系电话
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function applysale($uid, $id, $type = 0, $moneye, $cause = '', $instructions = '', $image = '', $phone, $gid = '')
    {
        $result = [
            'data'   => [],  //数据
            'msg'    => '',  // 返回信息
            'status' => false // 状态值
        ];
        $order = Order::get($id);
        try {
            Db::startTrans();
            // 如果没有商品id 就全部退款
            if (empty($gid))
            {
                if ($order['refund_amount'] != $moneye)
                {
                    $result['msg'] = '退款金额不对,请从新操作';
                }else{
                    $order->order_status = 5;
                    $order->refund       = 1;
                    $order->save();
                    OrderGoods::where('order_id',$id)->where('refund_status',0)->update(['refund_status' => 1]);
                    $orderlist = OrderGoods::where('order_id',$id)->select();

                    foreach ($orderlist as $key => $val)
                    {
                        $updata = [
                            'refund_sn' => $order['pay_sn'],
                            'order_id'  => $id,
                            'user_id'   => $uid,
                            'order_goods_id' => $val['id'],
                            'goods_id'  => $val['goods_id'],
                            'item_id'   => $val['sku_id'],
                            'goods_num' => $val['goods_num'],
                            'refund_reason' => $cause,
                            'refund_remark' => $instructions,
                            'refund_type'   => $type,
                            'refund_price'  => $val['price'],
                            'refund_image'  => $image,
                            'phone'         => $phone,
                            'status'        => $type == 1 ? 0 : 5,
                            'create_time'   => time(),
                        ];

                        Db::name('order_sale')->insertGetId($updata);
                    }
                    $result['status'] = true;
                }
            }else{
                $ordergoods = OrderGoods::where('order_id',$id)->where('id',$gid)->find();
                if (empty($ordergoods))
                {
                    $result['msg'] = '订单商品不存在';
                }else{
                    if ($ordergoods['price'] == $moneye)
                    {
                            $order_refund_data = [
                                'refund_sn' => $order['pay_sn'],
                                'user_id'   => $uid,
                                'order_id'  => $order['id'],
                                'order_goods_id' => $gid,
                                'goods_id'     => $ordergoods['goods_id'],
                                'item_id'      => $ordergoods['sku_id'],
                                'goods_num'    => $ordergoods['goods_num'],
                                'refund_reason' => $cause,
                                'refund_remark' => $instructions,
                                'refund_type'   => $type,
                                'status'        => $type == 1 ? 0 : 5,
                                'refund_price'  => $order['goods_pay_price'],
                                'refund_image'  => $image,
                                'phone'         => $phone,
                                'create_time'   => time(),
                            ];
                            Db::name('order_goods')->where('id',$gid)->update(['refund_status' => 1]);
                            Db::name('order_sale')->insertGetId($order_refund_data);
                        $result['status'] = true;
                    }else{
                        $result['msg'] = '金额不符';
                    }
                }
            }
            $count = OrderGoods::where('order_id',$id)->where('refund_status',0)->count();
            if ($count <= 1)
            {
                Order::where('id',$id)->update(['order_status' => 5, 'refund' => 1]);
            }
            if ($result['status'] == true)
            {
                Db::commit();
                $result['msg']    = '提交成功';
            }

        }catch(\Exception $e){
            Db::rollback();
            $result['msg'] = '申请失败';
        }

        return $result;
    }
    /**
     * @param $uid  用户id
     * @param $id  订单id
     * @return array|bool|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getsale($uid, $id, $gid)
    {
        $result = [
            'data' => null,
            'msg'  => '',
            'status' => false
        ];

        $ordersale = OrderSale::field('refund_reason,refund_remark,refund_image,phone,admin_remark',true)
            ->where('user_id',$uid)
            ->where('order_id',$id)
            ->where('order_goods_id',$gid)
            ->find();

        if (!$ordersale)
        {
            $result['msg'] = '售后信息不存在';
            return $result;
        }
        /**
         * 买家地址
         */
        $address = Db::name('order')->field('name,province,city,district,address,mobile,deliv_address,refund_address')
            ->where('id',$ordersale['order_id'])
            ->find();
        if (!empty($address['refund_address']))
        {
            $addressId = $address['refund_address'];
        }else{
            $addressId = $address['deliv_address'];
        }
        $refundAddress = Db::name('delivaddress')->where('id',$addressId)->find();

        $goods = Db::name('order_goods')
            ->field('goods_name,goods_num,goods_price,goods_image')
            ->where('id',$ordersale['order_goods_id'])
            ->find();
        $goods['spec_value_str'] = '';
        if ($ordersale['item_id'] != 0)
        {
            $goods['spec_value_str'] = Db::name('goods_item')->where('id',$ordersale['item_id'])->value('spec_value_str');
        }

        $data = [
            'address' => $refundAddress,
            'sale'    => $ordersale,
            'goods'   => $goods,
        ];

        return $data;

    }
    /**
     * @param $uid 用户id
     * @param $id  单号
     */
    public static function setlogistics($uid, $id, $invoice, $name)
    {
        $data = [
            'invoice_no'   => $invoice,
            'express_name' => $name,
            'status'       => 3,
            'update_time'  => time(),
        ];
        $response = OrderSale::where('id',$id)->where('user_id',$uid)->update($data);
        if ($response)
        {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 发表评论
     */
    public static function addrewview($uid, $params = [])
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false,
        ];
        $order = Order::get($params['id']);
        if (!$order)
        {
            $result['msg'] = '订单不存在';
            return $result;
        }
        if ($order['order_status'] < 3)
        {
            $result['msg'] = '您还未收货呢哦';
            return $result;
        }
        $order_goods = OrderGoods::where('id',$params['gid'])
            ->where('order_id',$params['id'])
            ->find();

        if (!$order_goods)
        {
            $result['msg'] = '请从新选择评论的商品';
            return $result;
        }
        if ($order_goods['is_comment'])
        {
            $result['msg'] = '您已评论,请在商品评论下查看';
            return $result;
        }

        $Usermodel = new Usermodel();
        $user = $Usermodel->getUserInfo($uid); // 查询用户信息
        
        if (!$user['data']){
            $result['msg'] = '用户不存在请从新操作';
            return $result;
        }

        $nickname = $user['data']['nickname'];
        $avatar   = $user['data']['avatar'];

        $time = time();
        try {
            Db::startTrans();
            // 评论商品
            $insertdata = [
                'uid'         => $uid,
                'gid'         => $order_goods['goods_id'],
                'order_id'    => $order_goods['order_id'],
                'content'     => $params['goods_comment'],
                'image'       => $params['goods_image'],
                'create_time' => $time,
                'goods_type'  => 'goods',
                'name'        => $nickname,
                'user_image'  => $avatar,
                'score'       => $params['goods_score'],
            ];
            $goodscomment = GoodsComment::create($insertdata);

            if ($goodscomment->id)
            {
                $order_goods->is_comment = 1;
                $order_goods->save();
                if ($params['sid'])
                {
                   $usershop = UserShop::get($params['sid']);
                   if (!empty($usershop))
                   {
                       $insertshopdata = [
                           'uid'         => $uid,
                           'gid'         => $params['sid'],
                           'order_id'    => $order_goods['order_id'],
                           'content'     => $params['goods_comment'],
                           'image'       => $params['goods_image'],
                           'create_time' => $time,
                           'goods_type'  => 'shop',
                           'name'        => $nickname,
                           'user_image'  => $avatar,
                           'score'       => $params['goods_score'],
                       ];
                       GoodsComment::create($insertshopdata);
                   }

                    $integral = Config::getSing(); // 积分
        //                                                             dump($user['is_vip']);
        // die;
                    switch ($user['is_vip'])
                    {
                        case  1:
                          $score = bcadd($user['data']['score'], $integral, 2);
                          $user_updata = [
                                'score'      => $score,
                                'updatetime' => $time,
                          ];
                          Integral::insert([
                                'uid'        => $uid,
                                'integral'   => $integral,
                                'type'       => 5,
                                'create_time'=> $time,
                                'is_type'    => 1
                          ]);
                            break;
                            case 0 :
                          $score = bcadd($user['data']['score'], $integral, 2);
                          $user_updata = [
                                'score'      => $score,
                                'updatetime' => $time,
                          ];
                          Integral::insert([
                                'uid'        => $uid,
                                'integral'   => $integral,
                                'type'       => 5,
                                'create_time'=> $time,
                                'is_type'    => 1
                          ]);
                            break;
                        case 2 || 3:
                            $money = bcadd($user['data']['money'], $integral, 2);
                            $user_updata = [
                                'money'      => $money,
                                'updatetime' => $time,
                            ];
                            Usermoney::create([
                                'uid'   =>  $uid,
                                'money' =>  $integral,
                                'type'  =>  'rewview',
                                'create_time'  =>  $time,
                                'is_type'      =>  1
                            ]);
                            break;

                    }

                    $Usermodel::where('id',$uid)->update($user_updata);
                    UserShop::where('id',$params['sid'])->setInc('credit_score',$params['shop_score']);
                }

                foreach($order as $key => $val){
                    $count = OrderGoods::where('order_id',$order['id'])->where('is_comment',0)->count();
                    if ($count == 0){
                        Order::where('id',$params['id'])->update([
                            'order_status'  => 4,
                            'update_time'   => $time,
                        ]);
                    }
                }

                Db::commit();
                $result['msg']    = '评论成功';
                $result['status'] = true;
            }else{
                Db::rollback();
                $result['msg'] = '评论失败';
            }
        }catch(\Exception $e){
            Db::rollback();
            var_dump($e->getLine());
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
}